/**
 * 描述：基础函数封装
 * 作者：jiajl
 */

(function ($) {
    $.ajaxSetup({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        cache: false,
        async: false
    });
    $.parameter = function (opts) {
        this.opts = opts;
    };
    $.extend($.parameter.prototype, {
        searchFastViewList: function (_this) {
            var options = this.opts;
            $("#" + options.searchFastBtn + "").click(function () {
                options.callback();
            });
            $("#searchName").keydown(function (event) {
                if (event.keyCode == 13) {
                    $("#" + options.searchFastBtn + "").click();
                    return false;
                }
            });
        },
        searchViewList: function (_this) {
            var options = this.opts;
            $("#" + options.searchBtn + "").click(function () {
                options.callback();
            });
        },
        resetViewList: function (_this) {
            var options = this.opts;
            $("#" + options.resetBtn + "").click(function () {
                var searchForm = options.searchForm;
                $("#" + searchForm + "")[0].reset();
                options.callback();
            });
        },
        addClick: function () {
            var options = this.opts;
            $("#" + options.addBtn + "").click(function () {
                var winUrl = options.editorUrl;
                if (options.openState) {
                    ymPrompt.win({
                        title: options.winTitle,
                        fixPosition: true,
                        maxBtn: false,
                        minBtn: false,
                        width: options.winWidth,
                        height: options.winHeight,
                        winPos: options.winPos,
                        message: winUrl,
                        iframe: true
                    });
                } else {
                    location.href = options.editorUrl;
                }
            });
        },
        delClick: function () {
            var options = this.opts;
            $("#" + options.delBtn + "").click(function () {

            });
        },
        backClick: function () {
            var options = this.opts;
            $("#" + options.backBtn + "").click(function () {
                location.href = options.returnUrl;
            });
        },
        closeClick: function () {
            var options = this.opts;
            $("#" + options.closeBtn + "").click(function () {
                window.parent.ymPrompt.doHandler('', true);
            });
        },
        saveOrModifyClick: function (_this, opts) {
            var _form = $(_this).attr("id");
            if (opts.submitBtn != undefined) {
                checkForm(_form);
            }
            $("#" + opts.submitBtn + "").click(function () {
                submitData(_this, opts, _form);
            });
        }
    });
    window.modifyClick = function (formId) {
        var options = window.opts;
        var winUrl = options.editorUrl;
        var index = winUrl.indexOf("?");
        if (index != -1) {
            winUrl += "&id=" + formId;
        } else {
            winUrl += "?id=" + formId;
        }
        if (options.openState) {
            ymPrompt.win({
                title: options.winTitle,
                fixPosition: true,
                maxBtn: false,
                minBtn: false,
                width: options.winWidth,
                height: options.winHeight,
                winPos: options.winPos,
                message: winUrl,
                iframe: true
            });
        } else {
            location.href = winUrl;
        }
    };
    window.viewClick = function (formId) {
        var options = window.opts;
        var winUrl = options.readUrl;
        var index = winUrl.indexOf("?");
        if (index != -1) {
            winUrl += "&id=" + formId;
        } else {
            winUrl += "?id=" + formId;
        }
        if (options.openState) {
            ymPrompt.win({
                title: options.winTitle,
                fixPosition: true,
                maxBtn: false,
                minBtn: false,
                width: options.winWidth,
                height: options.winHeight,
                winPos: options.winPos,
                message: winUrl,
                iframe: true
            });
        } else {
            location.href = winUrl;
        }
    };
    window.replyClick = function (formId) {
        var options = window.opts;
        var winUrl = options.replyUrl;
        var index = winUrl.indexOf("?");
        if (index != -1) {
            winUrl += "&id=" + formId;
        } else {
            winUrl += "?id=" + formId;
        }
        if (options.openState) {
            ymPrompt.win({
                title: options.winTitle,
                fixPosition: true,
                maxBtn: false,
                minBtn: false,
                width: options.winWidth,
                height: options.winHeight,
                winPos: options.winPos,
                message: winUrl,
                iframe: true
            });
        } else {
            location.href = winUrl;
        }
    };
    window.detailClick = function (formId) {
        alert(formId)
    };
    window.deleteClick = function (formId) {
        var options = window.opts;
        var winUrl = options.deleteUrl;
        var index = winUrl.indexOf("?");
        if (index != -1) {
            winUrl += "&id=" + formId;
        } else {
            winUrl += "?id=" + formId;
        }
        ymPrompt.confirmInfo({
            title: "操作确认提示框", message: "您确定要删除选中项吗？", width: 280, height: 160, handler: function (tp) {
                if (tp == 'ok') {
                    $.post(winUrl, function (msg) {
                        if (msg == "success") {
                            ymPrompt.succeedInfo({
                                title: "操作成功", message: "操作成功！", width: 280, height: 160, handler: function (tp) {
                                    if (tp == 'ok' || tp == 'close') {
                                        window.parent.ymPrompt.doHandler('', true);
                                        loadLocalPath(opts.returnUrl);
                                    }
                                }
                            });
                        } else if (msg == "faild") {
                            ymPrompt.alert({title: "温馨提示", message: "操作失败，请重新操作！", width: 280, height: 160});
                        } else {
                            ymPrompt.alert({title: "温馨提示", message: "系统异常，请联系管理员！", width: 280, height: 160});
                        }
                    });
                } else {
                    return false;
                }
            }
        });
    };
    window.regClick = function (formId) {
        var options = window.opts;
        var winUrl = options.regUrl;
        var index = winUrl.indexOf("?");
        if (index != -1) {
            winUrl += "&id=" + formId;
        } else {
            winUrl += "?id=" + formId;
        }
        ymPrompt.confirmInfo({
            title: "操作确认提示框", message: "确定通过认证吗？", width: 280, height: 160, handler: function (tp) {
                if (tp == 'ok') {
                    $.post(winUrl, function (msg) {
                        if (msg == "success") {
                            ymPrompt.succeedInfo({
                                title: "操作成功", message: "操作成功！", width: 280, height: 160, handler: function (tp) {
                                    if (tp == 'ok' || tp == 'close') {
                                        window.parent.ymPrompt.doHandler('', true);
                                        loadLocalPath(opts.returnUrl);
                                    }
                                }
                            });
                        } else if (msg == "faild") {
                            ymPrompt.alert({title: "温馨提示", message: "操作失败，请重新操作！", width: 280, height: 160});
                        } else {
                            ymPrompt.alert({title: "温馨提示", message: "系统异常，请联系管理员！", width: 280, height: 160});
                        }
                    });
                } else {
                    return false;
                }
            }
        });
    };
    var initSel = function (item) {
        $.each(item, function (key, o) {
            var sel = $("#" + o.selId + "");
            if (o.relation != undefined) {
                selRelation(o.relation, o.defaultValue);
            }
            if (o.selUrl == undefined) {
                sel.empty();
                sel.get(0).options.add(new Option("请选择", "" + o.defaultValue + ""));
                $.each(o.selJson, function (index, obj) {
                    sel.get(0).options.add(new Option(obj, index));
                });
                sel.change(function () {
                    if (o.selText != undefined) {
                        $("#" + o.selText + "").attr("value", sel.find("option:selected").text());
                    }
                    if (o.relation != undefined) {
                        selRelation(o.relation, this.value);
                    }
                });
            } else {
                $.getJSON(o.selUrl, function (data) {
                    sel.empty();
                    sel.get(0).options.add(new Option("请选择", "" + o.defaultValue + ""));
                    $.each(data, function (index, obj) {
                        sel.get(0).options.add(new Option(obj["" + o.selValue.value + ""], obj["" + o.selValue.id + ""]));
                    });
                });
                sel.change(function () {
                    if (o.selText != undefined) {
                        $("#" + o.selText + "").attr("value", sel.find("option:selected").text());
                    }
                    if (o.relation != undefined) {
                        selRelation(o.relation, this.value);
                    }
                });
            }
        });
    };
    var selRelation = function (relation, value) {
        var relationSel = $("#" + relation.selId + "");
        var relationUrl = relation.selUrl + value;
        $.getJSON(relationUrl, function (data) {
            relationSel.empty();
            relationSel.get(0).options.add(new Option("请选择", "" + relation.defaultValue + ""));
            $.each(data, function (index, obj) {
                relationSel.get(0).options.add(new Option(obj["" + relation.selValue.value + ""], obj["" + relation.selValue.id + ""]));
            });
        });
    };
    var openSel = function (item) {
        $.each(item, function (key, o) {
            var evt = o.event;
            if (evt == "dblclick") {
                $("#" + o.winTag + "").dblclick(function () {
                    var winUrl = o.winUrl;
                    var index = winUrl.indexOf("?");
                    if(index != -1){
                        winUrl += "&code="+o.winTag+"Code&name="+o.winTag;
                    }else{
                        winUrl += "?code="+o.winTag+"Code&name="+o.winTag;
                    }
                    ymPrompt.win({
                        title: o.winTitle,
                        fixPosition: true,
                        maxBtn: false,
                        minBtn: false,
                        width: o.winWidth,
                        height: o.winHeight,
                        winPos: o.winPos,
                        message: winUrl,
                        iframe: true
                    });
                });
            }
            if (evt == "click" || evt == undefined) {
                $("#" + o.winTag + "").click(function () {
                    var winUrl = o.winUrl;
                    var index = winUrl.indexOf("?");
                    if(index != -1){
                        winUrl += "&code="+o.winTag+"Code&name="+o.winTag;
                    }else{
                        winUrl += "?code="+o.winTag+"Code&name="+o.winTag;
                    }
                    ymPrompt.win({
                        title: o.winTitle,
                        fixPosition: true,
                        maxBtn: false,
                        minBtn: false,
                        width: o.winWidth,
                        height: o.winHeight,
                        winPos: o.winPos,
                        message: winUrl,
                        iframe: true
                    });
                });
            }
        });
    };
    var loadRelation = function (item) {
        $.each(item, function (i, o) {
            if (o.id != "") {
                $.getJSON(o.url + o.id, function (rs) {
                    if (rs != null) {
                        var defaultValue = "";
                        var defaultName = "";
                        var relation = $("#" + o.mark + "");
                        relation.empty();
                        $.each(rs, function (key, item) {
                            if (item.relationCode != null) {
                                defaultValue += item.relationType + item.relationCode + ",";
                                defaultName += item.relationName + ",";
                                relation.get(0).options.add(new Option("" + item.relationName + "", "" + item.relationType + "" + item.relationCode + ""));
                            }
                        });
                        var len1 = defaultValue.lastIndexOf(",");
                        var len2 = defaultName.lastIndexOf(",");
                        $("#" + o.code + "").attr("value", defaultValue.substring(defaultValue, len1));
                        $("#" + o.name + "").attr("value", defaultName.substring(defaultName, len2));
                    }
                });
            }
        });
    };
    var loadViewMotion = function (_this, opts) {
        var evt = new $.parameter(opts);
        evt.searchFastViewList(_this);// 快速搜索事件
        if (opts.searchForm != undefined) {
            evt.searchViewList(_this);// 搜索事件
            evt.resetViewList(_this);// 重置事件
        }
        evt.addClick();// 添加事件
        evt.delClick();// 删除事件
        if (opts.sel != undefined) {
            initSel(opts.sel);
        }
        if (opts.winSel != undefined) {
            openSel(opts.winSel);
        }
        if (opts.relation != undefined) {
            loadRelation(opts.relation);
        }
    };
    var loadEditMotion = function (_this, opts) {
        var evt = new $.parameter(opts);
        evt.saveOrModifyClick(_this, opts);// 保存OR修改事件
        if (opts.openState) {
            evt.closeClick();// 关闭事件
        } else {
            evt.backClick();// 返回事件
        }
        if (opts.sel != undefined) {
            initSel(opts.sel);
        }
        if (opts.winSel != undefined) {
            openSel(opts.winSel);
        }
        if (opts.relation != undefined) {
            loadRelation(opts.relation);
        }
    };
    //列表信息
    $.fn.loadViewList = function (opts) {
        loadViewMotion(this, opts);
        loadViewData(this, opts);
        var _this = $("#" + $(this).attr("id") + "");
        opts.callback = function () {
            _this.jqGrid('setGridParam').trigger("reloadGrid");
        };
    };
    //编辑信息
    $.fn.loadEditData = function (opts) {
        loadEditMotion(this, opts);
        if (opts.formId != "") {
            var item = loadDetailData(opts);
            jsonToForm(item);
        }
    };

    var loadDetailData = function (opts) {
        var item = null;
        var detailUrl = opts.detailUrl;
        if (detailUrl != undefined) {
            var index = detailUrl.indexOf("?");
            if (index != -1) {
                detailUrl += "&id=" + opts.formId;
            } else {
                detailUrl += "?id=" + opts.formId;
            }
            $.getJSON(detailUrl, function (result) {
                item = result;
            });
            return item;
        }
    };
    var jsonToForm = function (item) {
        for (var key in item) {
            var val = item[key] == null ? "" : item[key];
            if ($("[name=" + key + "]").get(0) != null) {
                var tag = $("[name=" + key + "]").get(0).tagName;
                if (tag == "INPUT") {
                    var elemType = $("input[name='" + key + "']").attr("type");
                    switch (elemType) {
                        case "radio":
                            $("input[name='" + key + "'][value='" + val + "']").attr("checked", true);
                            break;
                        case "checkbox":
                            var checkboxObj = $("input[name='" + key + "']:checkbox");
                            if (val != null) {
                                $.each(val, function (i, o) {
                                    for (var i = 0; i < checkboxObj.length; i++) {
                                        if (checkboxObj[i].value == o) {
                                            checkboxObj[i].checked = true;
                                        }
                                    }
                                    ;
                                });
                            }
                            break;
                        default:
                            $("#" + key + "").attr("value", val);
                            break;
                    }
                }
                if (tag == "SELECT") {
                    if ($("#" + key + " option[value='" + val + "']").length > 0) {
                        $("#" + key + " option[value='" + val + "']").attr("selected", "selected");
                    } else {
                        $("#" + key).append("<option>" + val + "</option>");
                    }
                }
                if (tag == "TEXTAREA") {
                    $("#" + key + "").text(val);
                }
                if (tag == "SPAN") {
                    $("#" + key + "").text(val);
                }
                if (tag == "DIV") {
                    $("#" + key + "").html(val);
                }
            }
        }
    };
    var submitData = function (_this, opts, _form) {
        if (checkAll(_form)) {
            var jsonData = $.toJSON($(_this).serializeObject());
            //alert(jsonData);
            $.post(opts.submitUrl, jsonData, function (msg) {
                if (msg == "success") {
                    ymPrompt.succeedInfo({
                        title: "温馨提示",
                        message: "恭喜您！操作成功！",
                        showShadow: false,
                        width: 280,
                        height: 150,
                        handler: function (tp) {
                            if (tp == 'ok' || tp == 'close') {
                                if (opts.openState) {
                                    window.parent.ymPrompt.doHandler('', true);
                                    loadLocalPath(opts.returnUrl);
                                } else {
                                    location.href = opts.returnUrl;
                                }
                            }
                        }
                    });
                } else if (msg == "faild") {
                    ymPrompt.alert({title: "温馨提示", message: "操作失败，请重新操作！", width: 280, height: 160});
                } else {
                    ymPrompt.alert({title: "温馨提示", message: "系统异常，请联系管理员！", width: 280, height: 160});
                }
            });
        }
    };
    //加载对象数据(from wxl)
    $.fn.loadObjectData = function (opts) {
        var objectUrl = opts.objectUrl;//回复url
        var item = null;
        if (objectUrl != undefined) {
            var index = objectUrl.indexOf("?");
            if (index != -1) {
                objectUrl += "&id=" + opts.formId;
            } else {
                objectUrl += "?id=" + opts.formId;
            }
            $.getJSON(objectUrl, function (result) {
                item = result;
            });
            return item;
        }
    }
    //加载消息视图
    $.fn.loadViewMsgList = function(optionsList,msgList){
        loadViewMsgList(optionsList,msgList);
    }
    //加载集合数据，进行分页获取(from wxl)
    $.fn.loadObjectList = function(opts){
        var page = "1";
        if(opts.page != undefined){
            page = opts.page;//当前页
        }
        var row = "5";
        if(opts.row != undefined){
            row = opts.row;//每页数据
        }
        var objectUrl  = opts.objectUrl;//回复url
        var item = null;
        if(objectUrl != undefined){
            var index = objectUrl.indexOf("?");
            if(opts.sid != undefined){
                if(index != -1){
                    objectUrl += "&id="+opts.formId+"&page="+page+"&row="+row;
                }else{
                    objectUrl += "?id="+opts.formId+"&page="+page+"&row="+row;
                }
            }else{
                if(index != -1){
                    objectUrl += "&id="+opts.formId+"&page="+page+"&row="+row+"&sidx="+opts.sidx;
                }else{
                    objectUrl += "?id="+opts.formId+"&page="+page+"&row="+row+"&sidx="+opts.sidx;
                }
            }

            $.getJSON(objectUrl, function(result) {
                item = result;
            });
            return item;
        }
    }
})(jQuery);